﻿package com.guavestudios.fcfg.readers {
	import adobe.utils.CustomActions;
	import com.guavestudios.fcfg.readers.BasicSettingReader;
	
	/**
	 * ...
	 * @author maze | guavestudios.com
	 */
	public class FcfgXmlReader extends BasicSettingReader implements ISettingReader{
		
		protected var elemId:String = "id";
		protected var elemSelect:String = "setting";
		protected var elemValue:String = "";
		public function FcfgXmlReader(xml:XML = null, searchfnc:Function = null) {
			if (searchfnc == null) searchfnc = defaultFunction;
			if (xml != null)
				load(xml, defaultFunction);
		}
		
		override public function load(...args):void {
			//check params
			var xml:XML;
			var searchFunc:Function = defaultFunction
			if (args.length > 0) xml = args[0];
			if (args.length > 1) searchFunc = args[1];
			
			if (xml == null) return;
			
			var xl:XMLList = searchFunc(xml);
			for each (var x:XML in xl) {
				setSetting(mapIdRev(x.attribute(elemId).toString()),getXmlValue(x));
			}
			
		}
		protected function getXmlValue(x:XML):*{
			var ret:*= x.toString();
			if (x.@type != undefined) {
				switch (x.@type.toString()) {
					case "int": return parseInt(ret);
					case "number": return parseFloat(ret);
					case "boolean":return ret == "true";
					case "date":return new Date(Date.parse(ret));
				}
			}
			return ret;
		}
		
		protected function defaultFunction(xml:XML):XMLList {
			return xml.child(elemSelect);
		}
	}
}